#include "explosionParticle.h"


explosionParticle::explosionParticle(ofxVec2f pos)
{
    target = NULL;

	position = pos;

    dead=false;
    fadedOut = false;
    fadeAlphaMod = 1.0f;
	gaveMass = false;
	lost = false;

	timeToDie = ofGetElapsedTimef()+settings::TIME_TO_LIVE_AFTER_SPAWN;

	radius = 2+rand()%4;
	explode();
}


explosionParticle::~explosionParticle(void)
{
}



int explosionParticle::update()
{
	if(lost && timeToDie-settings::TIME_TO_LIVE_AFTER_SPAWN+settings::TIME_TO_LIVE_AFTER_SPAWN_LOST<ofGetElapsedTimef())
        dead = true;
	else if(target != NULL && timeToDie<ofGetElapsedTimef() && (target->dead || lost ))
        dead = true;

    //if(target != NULL) targetPos = target->getPosition();

    ofxVec2f diff = (targetPos-position);


    if(!lost)
        velocity +=diff.normalized()*acceleration;

		//velocity += velocity.normalized()*acceleration;
	//velocity+=ofxVec2f(ofRandom(-0.1f,0.1f),ofRandom(-0.1f,0.1f))*PARTICLE_SPEED;

	//velocity *= friction;

	ofxVec2f maxVel = velocity;
	if(maxVel.length()>maxVelocity)
		maxVel = maxVel.normalized()*maxVelocity;


	position +=maxVel*testApp::deltaTime;

	return 1;
}

void explosionParticle::updateAndDraw(ofxVec2f newTarget, bool fadedOut, float fadeAlphaMod)
{
    this->fadeAlphaMod = fadeAlphaMod;
    this->targetPos = newTarget;
    this->fadedOut = fadedOut;

    update();
    draw();
}

void explosionParticle::draw()
{
	if(dead && fadedOut)
		return;

    if(lost)
    {
        float FadedOutAt = timeToDie-settings::TIME_TO_LIVE_AFTER_SPAWN+settings::TIME_TO_LIVE_AFTER_SPAWN_LOST;
        fadeAlphaMod = (FadedOutAt-ofGetElapsedTimef())/(settings::TIME_TO_LIVE_AFTER_SPAWN+settings::TIME_TO_LIVE_AFTER_SPAWN_LOST);
        ofSetColor(50,200,200,200*fadeAlphaMod);

    }
    else
        ofSetColor(200,100,100,150*fadeAlphaMod);


	ofCircle(position.x,position.y,radius);
}


void explosionParticle::setTarget(blob* newTarget)
{
	target = newTarget;
}

void explosionParticle::setTarget(ofxVec2f newTarget)
{
	targetPos = newTarget;
}
void explosionParticle::explode()
{
	velocity = ofxVec2f(0,0);
	acceleration = ofRandom(0.5f,2.0f)*settings::PARTICLE_SPEED*20;
	velocity=ofxVec2f(ofRandom(-1.0f,1.0f),ofRandom(-1.0f,1.0f));
	velocity.normalize();
	velocity *= ofRandom(1.0f,10.0f)*(10);
	friction = 1;//ofRandom(0.96f,0.99f);
	gaveMass = false;
	maxVelocity = settings::PARTICLE_MAX_SPEED+ofRandom(0.0f,100);

}
